package cn.enjoyedu.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author King老师   享学课堂 https://enjoy.ke.qq.com
 * 往期课程咨询芊芊老师  QQ：2130753077 VIP课程咨询 依娜老师  QQ：2133576719
 * 类说明：
 */
@Configuration
@EnableKafka
public class KafkaProducerConfig {
    @Value("${kafka.producer.servers}")
    private String servers;
    @Value("${kafka.producer.retries}")
    private int retries;
    @Value("${kafka.producer.batch.size}")
    private int batchSize;
    @Value("${kafka.producer.linger}")
    private int linger;
    @Value("${kafka.producer.buffer.memory}")
    private int bufferMemory;
    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {

        Map<String, Object> props = new HashMap<>(16);
        //必备
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        
        props.put(ProducerConfig.RETRIES_CONFIG, retries);//重试改成0次
        //一个分区的批次
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);//得到这个大小 再一批发出去
        props.put(ProducerConfig.LINGER_MS_CONFIG, linger);//等待时间

        //发送缓存默认32M 不够就阻塞max.block.ms 阻塞时间到了还不行, 异常
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        
        
        KafkaTemplate kafkaTemplate = new KafkaTemplate<>(new DefaultKafkaProducerFactory<String, String>(props)) ;
        //kafkaTemplate.setProducerListener();
        return kafkaTemplate;
    }
}
